﻿using System.Net;
using System.Web.Hosting;
using System.Threading;
namespace System.Web
{
    public class WebHost : HttpListenerHost
    {
        private Type _httpApplicationType;
        private WebHostRuntime _runtime;
        private NetHttpApplicationFactory _applicationFactory;
        private NetHttpModuleCollection _modules = new NetHttpModuleCollection();
        private NetHttpHandlerCollection _handlers = new NetHttpHandlerCollection();

        public WebHost(Type httpApplicationType)
            : this(httpApplicationType, null) { }
        public WebHost(Type httpApplicationType, string uriPrefix)
            : base(null, uriPrefix)
        {
            //UseThreading = true;
            if (httpApplicationType == null)
                throw new ArgumentNullException("httpApplicationType");
            if (!typeof(NetHttpApplication).IsAssignableFrom(httpApplicationType))
                throw new ArgumentOutOfRangeException("httpApplicationType", "must be of type NetHttpApplication");
            _httpApplicationType = httpApplicationType;
            _applicationFactory = new NetHttpApplicationFactory(_httpApplicationType);
            _runtime = new WebHostRuntime(this);
        }

        public override void Open()
        {
            base.Open();
            if (Listener != null)
                _runtime.StartProcessing();
        }

        public override void Close()
        {
            base.Close();
            if (Listener != null)
                _runtime.StopProcessing();
        }

        public NetHttpModuleCollection Modules
        {
            get { return _modules; }
        }

        public NetHttpHandlerCollection Handlers
        {
            get { return _handlers; }
        }

        protected override HttpListenerWorkerRequest CreateWorkerRequest(HttpListenerContext netContext)
        {
            return _runtime.CreateWorkerRequest(netContext);
        }

        internal override void ProcessRequestNow(HttpListenerWorkerRequest wr)
        {
            _runtime.ProcessRequestNow((WebHostWorkerRequest)wr, _applicationFactory);
        }

        internal override void RejectRequestNow(HttpListenerWorkerRequest wr, bool silent)
        {
            NetHttpRuntime.RejectRequestNow(this, (WebHostWorkerRequest)wr, silent);
        }
    }
}
